import { useEffect, useRef } from "react";

const RandomTree = ({
  zoom = 0.5,
  className = "",
}: {
  zoom?: number;
  className?: string;
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  /**
   *@param {[number,number]} start  启点座标
   *@param {number} length 长度
   *@param {number} thick  粗细
   *@param {number} angle  夹角
   */
  const drawBeanch = (
    ctx: CanvasRenderingContext2D,
    start: [number, number],
    length: number,
    thick: number,
    angle: number
  ) => {
    if (thick < 5 * zoom && Math.random() < 0.2) {
      return;
    }
    //画花
    if (thick < 2 * zoom) {
      ctx.beginPath();
      ctx.arc(...start, 10 * zoom, 0, 2 * Math.PI);
      ctx.fillStyle = "#fff";
      ctx.fill();
      ctx.arc(
        ...[start[0] - 1 * zoom, start[1] - 6 * zoom],
        8 * zoom,
        0,
        2 * Math.PI,
        true
      );
      ctx.fillStyle = "red";
      ctx.fill();
      return;
    }
    ctx.beginPath();
    //画起点坐标
    ctx.moveTo(...start);
    //计算终点坐标
    const end: [number, number] = [
      start[0] + length * Math.cos((angle * Math.PI) / 180),
      start[1] + length * Math.sin((angle * Math.PI) / 180),
    ];
    //画终点坐标
    ctx.lineTo(...end);
    //设置线段样式
    ctx.strokeStyle = "#333";
    ctx.lineWidth = thick;
    ctx.lineCap = "round";
    ctx.stroke();
    //左分支
    drawBeanch(ctx, end, length * 0.8, thick * 0.9, angle + Math.random() * 50);

    //右分支
    drawBeanch(ctx, end, length * 0.8, thick * 0.8, angle - Math.random() * 20/* 树叉的偏斜角度 */);
  };
  const init = () => {
    const canvas = canvasRef.current as HTMLCanvasElement;
    const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
    canvas.width = 600* zoom ; //window.innerWidth * devicePixelRatio;
    canvas.height = 500 * zoom; //  window.innerHeight * devicePixelRatio;
    //移动坐标系   （最初坐标系是↓→）
    ctx?.translate(canvas.width / 2, canvas.height);
    //改变Y坐标的方向
    ctx?.scale(1, -1);
    drawBeanch(ctx, [0, 0], 100 * zoom, 10 * zoom, 90);
  };
  useEffect(() => {
    init();
  }, []);
  return <canvas className={className} ref={canvasRef}></canvas>;
};
export default RandomTree;
